<template>
  <view>
    <!-- 商品列表 -->
    <view class="goods-list" v-if="!show && goodsList.length > 0">
      <block v-for="goods in goodsList" :key="goods.goods_id">
        <my-goods-item :goods="goods" @click="goToGoodsDetail(goods.goods_id)"></my-goods-item>
      </block>
    </view>
    
    <view class="empty" v-else>暂无商品列表数据</view>
  </view>
</template>

<script>
import { getGoodsListApi } from '@/api/good.js';
import MyGoodsItem from '@/components/my-goods/my-goods.vue';

export default {
  components: {
    'my-goods-item': MyGoodsItem
  },
  data() {
    return {
      queryParams: {
        query: '',
        cid: '',
        pagenum: 1,
        pagesize: 8
      },
      goodsList: [],
      total: 0,
      loading: true,
      show: false
    };
  },
  onLoad(options) {
    // console.log('🔄 页面加载参数:', options);
    if (options.query) {
      this.queryParams.query = options.query;
    }
    if (options.cid) {
      this.queryParams.cid = options.cid;
    }
    
    // 如果没有参数，设置默认搜索词
    if (!this.queryParams.query && !this.queryParams.cid) {
      this.queryParams.query = '手机';
    }
    
    // console.log('📤 最终请求参数:', this.queryParams);
    this.getGoodsList();
  },
  onReachBottom() {
    if (this.queryParams.pagenum * this.queryParams.pagesize >= this.total) {
      uni.$showMsg('数据加载完毕');
      return;
    }
    this.queryParams.pagenum++;
    this.getGoodsList();
  },
  onPullDownRefresh() {
    this.queryParams.pagenum = 1;
    this.total = 0;
    this.goodsList = [];
    this.loading = true;
    this.getGoodsList(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    async getGoodsList(cb) {
      if (this.loading) {
        this.loading = false;
        try {
          // console.log('🚀 发送API请求，参数:', this.queryParams);
          const res = await getGoodsListApi(this.queryParams);
          // console.log('📦 API完整响应:', res);
          
          let goodsData = [];
          let totalCount = 0;
          
          // 根据实际API响应结构：{total: 35, pagenum: "1", goods: [...]}
          if (res && res.message && res.message.goods) {
              // 格式：商品数据在 message 对象中
              // console.log('✅ API返回格式: message中包含goods');
              goodsData = res.message.goods;
              totalCount = res.message.total || 0;
          } else if (res && res.goods) {
              // 备用格式：直接包含 goods
              // console.log('✅ API返回格式: 直接包含goods');
              goodsData = res.goods;
              totalCount = res.total || 0;
          } else {
              // console.warn('❌ 未知的API响应格式:', res);
              goodsData = [];
              totalCount = 0;
          }
          
          // console.log(`📈 解析结果: ${goodsData.length}个商品，总数: ${totalCount}`);
          
          // 合并数据
          this.goodsList = [...this.goodsList, ...goodsData];
          this.total = totalCount;
          
          if (this.goodsList.length > 0) {
            this.show = false;
            // console.log('🎉 商品列表更新成功，共', this.goodsList.length, '个商品');
          } else {
            this.show = true;
            // console.log('😞 商品列表为空');
			
          }
        } catch (error) {
          // console.error('💥 获取商品列表失败:', error);
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          });
          this.show = true;
        } finally {
          this.loading = true;
          cb && cb();
        }
      }
    },
    goToGoodsDetail(goods_id) {
      uni.navigateTo({
        url: `/subpkg/goods_detail/goods_detail?goods_id=${goods_id}`
      });
    }
  }
};
</script>

<style lang="scss">
.goods-list {
  padding: 20rpx;
  background: #f5f5f5;
}

.empty {
  width: 400rpx;
  height: 400rpx;
  text-align: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #999;
  font-size: 28rpx;
}
</style>